<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>手势画图</title>
  <style>
    body, html { margin: 0; overflow: hidden; background: #000; }
    video, canvas {
      position: absolute;
      top: 0; left: 0;
      width: 100vw;
      height: 100vh;
      object-fit: cover;
    }
  </style>
</head>
<body>
  <video id="video" autoplay muted playsinline></video>
  <canvas id="canvas"></canvas>

  <script type="module">
    import { HandLandmarker, FilesetResolver } from 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0';

    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    let lastX = null, lastY = null;
    let drawing = false;

    async function init() {
      const vision = await FilesetResolver.forVisionTasks(
        'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm'
      );

      const handLandmarker = await HandLandmarker.createFromOptions(vision, {
        baseOptions: {
          modelAssetPath: `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/hand_landmarker.task`
        },
        runningMode: 'VIDEO',
        numHands: 1
      });

      // 启动摄像头
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      video.srcObject = stream;

      video.onloadedmetadata = () => {
        video.play();
        loop();
      };

      function loop() {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        handLandmarker.detectForVideo(video, performance.now()).then(result => {
          const landmarks = result.landmarks?.[0];
          if (landmarks) {
            const x = landmarks[8].x * canvas.width;
            const y = landmarks[8].y * canvas.height;

            // 判断是否“点击绘图”：拇指和食指距离小于阈值
            const dx = (landmarks[4].x - landmarks[8].x) * canvas.width;
            const dy = (landmarks[4].y - landmarks[8].y) * canvas.height;
            const distance = Math.sqrt(dx * dx + dy * dy);
            drawing = distance < 50;

            if (drawing && lastX !== null) {
              ctx.strokeStyle = '#00FF00';
              ctx.lineWidth = 4;
              ctx.beginPath();
              ctx.moveTo(lastX, lastY);
              ctx.lineTo(x, y);
              ctx.stroke();
            }

            lastX = x;
            lastY = y;
          } else {
            lastX = lastY = null;
            drawing = false;
          }

          requestAnimationFrame(loop);
        });
      }
    }

    init();
  </script>
</body>
</html>
